package com.sensor.Fragment;

import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import com.landmesure.bluetoothchat.LandCommunicationService;
import com.landmesure.bluetoothchat.R;
import com.landmesure.communication.CommunicationPlatform;
import com.landmesure.communication.ManagerFactory;
import com.landmesure.core.TestMessage;
import com.sensor.Manager.GangXuanShiShenYaJiManager;
import com.sensor.core.HandlerMessage;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ShenYaJiFragment extends Fragment {
    private final String TAG = "ShenYaJiFragment";
    private Spinner cehuiSpinner;
    private Spinner yaliSpinner;
    private Spinner projectSpinner;
    private Handler handler;
    private Context mContext;
    private Button startButton;
    private Button saveButton;
    private Button getGroupButton;
    private EditText stationEditText;
    private EditText groupEditText;
    private EditText overTimeEditText;
    private EditText timesEditText;
    private EditText yaliValueEditText;
    private EditText sensor1EditText;
    private EditText sensor2EditText;
    private EditText sensor3EditText;
    private EditText sensor4EditText;
    private EditText sensor5EditText;
    private EditText sensor6EditText;
    private EditText sensor7EditText;
    private EditText sensor8EditText;
    private EditText sensor9EditText;
    public static LandCommunicationService landCommunicationServiceInstance;    //设备管理服务实例
    private ArrayAdapter<String> adapter;
    private int station;
    private int group;
    private int pcode;
    private int biaoZhunYaLi;
    private int times;
    private List<EditText> listEditText = new ArrayList<>();
    private Map<Integer, EditText> sensor2EditMap;
    private int cehui;
    private ProgressDialog mDialog;
    private GangXuanShiShenYaJiManager gangXuanShiShenYaJiManager;
    private boolean mIsBind;
    private ServiceConnection mServiceConnection;
    public ShenYaJiFragment() {
        System.out.println(TAG + ":MyFragment()");
    }

    class MyServiceConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder iBinder) {
            LandCommunicationService.MyBinder myBinder;
            myBinder = (LandCommunicationService.MyBinder) iBinder;
            landCommunicationServiceInstance = myBinder.getInstance();
            landCommunicationServiceInstance.setBaseManager(gangXuanShiShenYaJiManager);
            mIsBind=true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        //启动设备管理服务，并绑定它
        Intent intent = new Intent(mContext, LandCommunicationService.class);
        mContext.startService(intent);
        mContext.bindService(intent, mServiceConnection=new MyServiceConn(), Context.BIND_AUTO_CREATE);
        handler = new MyHandler();
        CommunicationPlatform.handler = handler;
        gangXuanShiShenYaJiManager = (GangXuanShiShenYaJiManager) ManagerFactory.getRealManager("钢铉式渗压计检测", handler);
        Log.i(TAG, "onCreate: ------------");
    }

    //重写该方法，返回值View将作为Fragment显示的组件
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //加载fragment_main.xml布局文件
        View rootView = inflater.inflate(R.layout.layout_shenyaji_fragment, container, false);
        initView(rootView);
        setListener();
        init();
        Log.i(TAG, "onCreateView: ------------");
        return rootView;
    }

    private void initView(View rootView) {
        adapter = new ArrayAdapter<>(getActivity(), R.layout.spinner_item2, R.id.spinner_item_tv2, gangXuanShiShenYaJiManager.projectList);
        cehuiSpinner = rootView.findViewById(R.id.cehui);
        projectSpinner = rootView.findViewById(R.id.project);
        yaliSpinner = rootView.findViewById(R.id.yali);
        startButton = rootView.findViewById(R.id.button_start);
        saveButton = rootView.findViewById(R.id.button_save);
        getGroupButton = rootView.findViewById(R.id.get_group);
        stationEditText = rootView.findViewById(R.id.station);
        groupEditText = rootView.findViewById(R.id.group);
        timesEditText = rootView.findViewById(R.id.times);
        overTimeEditText = rootView.findViewById(R.id.over_time);
        yaliValueEditText = rootView.findViewById(R.id.yali_value);
        sensor1EditText = rootView.findViewById(R.id.sensor1_value);
        sensor2EditText = rootView.findViewById(R.id.sensor2_value);
        sensor3EditText = rootView.findViewById(R.id.sensor3_value);
        sensor4EditText = rootView.findViewById(R.id.sensor4_value);
        sensor5EditText = rootView.findViewById(R.id.sensor5_value);
        sensor6EditText = rootView.findViewById(R.id.sensor6_value);
        sensor7EditText = rootView.findViewById(R.id.sensor7_value);
        sensor8EditText = rootView.findViewById(R.id.sensor8_value);
        sensor9EditText = rootView.findViewById(R.id.sensor9_value);
        addEditText2List();


    }

    private void addEditText2List() {
        listEditText.add(sensor1EditText);
        listEditText.add(sensor2EditText);
        listEditText.add(sensor3EditText);
        listEditText.add(sensor4EditText);
        listEditText.add(sensor5EditText);
        listEditText.add(sensor6EditText);
        listEditText.add(sensor7EditText);
        listEditText.add(sensor8EditText);
        listEditText.add(sensor9EditText);
    }

    private void clearSensorEditText() {
        for (EditText e : listEditText) {
            e.setText(StringUtils.EMPTY);
        }
    }

    private void setListener() {
        startButton.setOnClickListener(new MyButtonClick());
        saveButton.setOnClickListener(new MyButtonClick());
        getGroupButton.setOnClickListener(new MyButtonClick());
        projectSpinner.setOnItemSelectedListener(new MySpinnerSelect());
        cehuiSpinner.setOnItemSelectedListener(new MySpinnerSelect());
        yaliSpinner.setOnItemSelectedListener(new MySpinnerSelect());
    }

    private void init() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                gangXuanShiShenYaJiManager.serProject(projectSpinner, adapter);
                gangXuanShiShenYaJiManager.getGroup();
            }
        }).start();


    }
    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {

            super.handleMessage(msg);
            switch (msg.what) {
                case HandlerMessage.ShengYaJi.READ_BZDL: {
                    Bundle data = msg.getData();
                    TestMessage testMessage = (TestMessage) data.getSerializable("data");
                    if (testMessage != null) {
                        yaliValueEditText.setText(testMessage.getValue());
                    }
                }
                break;
                case HandlerMessage.ShengYaJi.READ_SYJ: {
                    Bundle data = msg.getData();
                    TestMessage testMessage = (TestMessage) data.getSerializable("data");
                    if (null != testMessage) {
                        EditText editText = sensor2EditMap.get(testMessage.getEcode());
                        editText.setText(testMessage.getValue());
                    }
                    if (gangXuanShiShenYaJiManager.currentTimes == gangXuanShiShenYaJiManager.senSors.size() * times) {
                        closeProcessDialog();
                        showTip("测量完成");
                    }
                    break;
                }

                case HandlerMessage.ShengYaJi.SAVE_SYJ_DATA_SUCCESS: {
                    Bundle data = msg.getData();
                    showTip(data.getString("data"));
                    break;
                }
                case HandlerMessage.ShengYaJi.SAVE_DATA_ERROR: {
                    showTip("保存数据失败");
                    break;
                }
                case HandlerMessage.ShengYaJi.GET_GROUP_ERROR: {
                    showTip("查询分组信息失败");
                    break;
                }
                case HandlerMessage.ShengYaJi.GET_GROUP_SUCCESS: {
                    showTip("查询分组信息成功");
                    break;
                }
                case HandlerMessage.ShengYaJi.SER_PROJECT_ERROR: {
                    showTip("查询工程信息失败");
                    break;
                }
                default:
                    break;
            }
        }
    }
    private class MySpinnerSelect implements AdapterView.OnItemSelectedListener {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            onMySpinnerSelect(adapterView, view, i, l);
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    }

    private void onMySpinnerSelect(AdapterView<?> adapterView, View view, int pos, long l) {
        switch (adapterView.getId()) {
            case R.id.project:
                pcode = gangXuanShiShenYaJiManager.projectMap.get(gangXuanShiShenYaJiManager.projectList.get(pos));
                break;
            case R.id.cehui:
                cehui = Integer.parseInt(cehuiSpinner.getSelectedItem().toString());
                break;
            case R.id.yali:
                biaoZhunYaLi = Integer.parseInt(yaliSpinner.getSelectedItem().toString());
                break;
        }
    }

    private class MyButtonClick implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            onMyButtonClick(v);
        }

    }

    public void onMyButtonClick(View view) {
        switch (view.getId()) {
            case R.id.get_group: {
                    gangXuanShiShenYaJiManager.getGroup();
                break;
            }
            case R.id.button_start: {
                if (checkAll()) {
                    CommunicationPlatform.SLEEP_TIME = Integer.parseInt(String.valueOf(overTimeEditText.getText())) * 1000;
                    CommunicationPlatform.OVER_TIME = Integer.parseInt(String.valueOf(overTimeEditText.getText())) * 1000;
                    showProcessDialog(mContext);
                    bindSensorToEdit();
                    //清空edittext数据
                    clearSensorEditText();
                    gangXuanShiShenYaJiManager.readStart(times, station, group);
                }

                break;
            }
            case R.id.button_save: {
                String value = String.valueOf(yaliValueEditText.getText());
                if ("".equals(value)){
                    showTip("无标准压力值");
                    return;
                }
                gangXuanShiShenYaJiManager.save(cehui, pcode, biaoZhunYaLi,Double.parseDouble(value));

            }
        }
    }


    private void bindSensorToEdit() {
        sensor2EditMap = new HashMap<>();
        for (int i = 0; i < gangXuanShiShenYaJiManager.senSors.size(); i++) {
            sensor2EditMap.put(gangXuanShiShenYaJiManager.senSors.get(i).getEcode(), listEditText.get(i));
        }
    }

    private boolean checkStationGroup() {
        if ("".equals(stationEditText.getText().toString()) || "".equals(groupEditText.getText().toString())) {
            showTip("请填写站号板号");
            return false;
        } else {
            station = Integer.parseInt(stationEditText.getText().toString());
            group = Integer.parseInt(groupEditText.getText().toString());
        }
        return true;
    }

    private boolean checkAll() {
        if (gangXuanShiShenYaJiManager.senSors.isEmpty()){
            showTip("未查到分组配置信息");
            return false;
        }
        if ("".equals(timesEditText.getText().toString()) || "".equals(overTimeEditText.getText().toString())) {
            showTip("请填写测量次数超时时间");
            return false;
        } else {
            times = Integer.parseInt(timesEditText.getText().toString());
        }
        return checkStationGroup();
    }

    private void showTip(String messsage) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext).setTitle("提示")
                .setMessage(messsage);
        builder.create().show();


    }
    private void showProcessDialog(Context mContext) {

        // 声明一个等待框以提示用户等待
        mDialog = new ProgressDialog(mContext);
        mDialog.setTitle("提示信息");
        mDialog.setMessage("正在读取，请稍后...");
        mDialog.show();
        mDialog.setCancelable(false);
    }

    private void closeProcessDialog() {
        if (mDialog != null) {
            mDialog.setCancelable(true);
            mDialog.dismiss();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.i(TAG, "onStart: ------------");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "onResume: ----------");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.i(TAG, "onPause: -----------");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i(TAG, "onStop: -----------");
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        Log.i(TAG, "onDestroy: -----------");
        if (mIsBind)
            mContext.unbindService(mServiceConnection);
    }
}